package control.control.authmanage;


import base.bean.StandardResponse;
import base.standard.constant.message.MessageCode;
import base.util.BeanUtil;
import base.util.ResponseUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import control.module.bo.authmanage.UserRoleBo;
import control.module.po.authmanage.UserRole;
import control.module.vo.authmanage.UserRoleVO;
import control.service.IRoleService;
import control.service.IUserRoleService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Optional;

/**
 * <p>
 * 用户角色表(用户绑定角色) 前端控制器
 * </p>
 *
 * @author cyj
 * @since 2020-10-21
 */
@RestController
@RequestMapping("/user/role/{userId}")
@ResponseStatus(code = HttpStatus.OK)
@Slf4j
@Transactional(rollbackFor = Exception.class)
public class UserRoleController {

    @Autowired
    private IUserRoleService userRoleService;

    @Autowired
    private IRoleService roleService;

    @GetMapping("/all")
    public StandardResponse getUserRoles(Page page, @PathVariable Integer userId) {
        IPage<UserRole> list = userRoleService.page(page, new QueryWrapper<>(new UserRole().setUserId(userId)));
        IPage<UserRoleVO> userRoleVos = BeanUtil.newInstanceAndCopyBatch(list, UserRoleVO.class);
        userRoleVos.getRecords().stream().forEach(userRoleVO ->
                Optional.ofNullable(roleService.getById(userRoleVO.getRoleId())).ifPresent(role -> {
                    userRoleVO.setRoleName(role.getRoleName());
                }));
        return ResponseUtil.success(userRoleVos);
    }

    @PostMapping
    public StandardResponse saveUserRoles(@PathVariable Integer userId,
                                          @RequestBody @Validated List<UserRoleBo> userRoleBos) {
        boolean deleteResult = userRoleService.removeByUserId(userId);
        log.info("delete [{}] roles", userId);
        List<UserRole> userRoles = BeanUtil.newInstanceAndCopyBatch(userRoleBos, UserRole.class);
        boolean saveResult = userRoleService.saveBatch(userRoles);
        log.info("save [{}] roles", userId);
        return ResponseUtil.success(MessageCode.USER_ROLE_SAVE, saveResult);
    }
}

